<!-- 采购订单 -->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
      <el-form-item label="单据时间" prop="workstationName">
        <el-select v-model="queryParams.lastDays" placeholder="请选择单据时间">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="采购单据编号" prop="poCode">
        <el-input
          v-model="queryParams.poCode"
          placeholder="请输入采购单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商简称" prop="vendorNick">
        <el-input
          v-model="queryParams.vendorNick"
          placeholder="请输入供应商简称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item >
        <el-radio-group v-model="queryParams.poStatusList">
          <!-- <el-radio :label="3">全部订单</el-radio> -->
          <el-radio :label="'not_in'">从未交货</el-radio>
          <el-radio :label="'part_in'">部分交货</el-radio>
          <el-radio :label="'all_in'">完全交货</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item >
        <el-radio-group v-model="queryParams.poCheckStatusList">
          <el-radio :label="3">全部订单</el-radio>
          <el-radio :label="'not_chk'">从未验收</el-radio>
          <el-radio :label="'part_chk'">部分验收</el-radio>
          <el-radio :label="'all_chk'">完全验收</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleUpdate"
          >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >反审核</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleInput"
        >导入</el-button>
      </el-col> -->
      <right-toolbar @queryTable="getList"></right-toolbar>
    </el-row>

    <vxe-table
      border
      stripe
      v-loading="loading" 
      ref="tableRef"
      size="small"
      header-align="center"
      :row-config="rowConfig"
      :column-config="columnConfig"
      @checkbox-change="checkboxChangeEvent"
      @checkbox-all="checkboxAll"
      @cell-click="cellClickEvent"
      :data="purchaseOrderList"
    >
      <vxe-column type="checkbox" width="80" fixed="left" drag-sort></vxe-column>
      <vxe-column field="poCode" width="150" show-overflow="title" align="center" title="采购单据编号"></vxe-column>
      <!-- <vxe-column field="orderStatusDesc" width="100" show-overflow="title" align="center" title="单据状态"></vxe-column> -->
      <vxe-column field="poType" width="160" show-overflow="title" align="center" title="采购申请类型">
        <template #default="{ row }">
          <dict-tag :options="dict.type.purchase_request_status" :value="row.poType" />
        </template>
      </vxe-column>
      <vxe-column field="warehouseName" show-overflow="title" align="center" title="需求仓库" width="120"></vxe-column>
      <vxe-column field="vendorCode" width="120" show-overflow="title" align="center" title="供应商代码"></vxe-column>
      <vxe-column field="vendorNick" width="120" show-overflow="title" align="center" title="供应商简称"></vxe-column>
      <vxe-column field="principal" width="160" show-overflow="title" align="center" title="供应商负责人"></vxe-column>
      <vxe-column field="vendorContact" width="160" show-overflow="title" align="center" title="供应商联系人" ></vxe-column>
      <vxe-column field="purchaser" show-overflow="title" align="center" title="采购员" width="120"></vxe-column>
      <vxe-column show-overflow="title" align="center" title="制单日期" width="120">
        <template #default="{ row }">
          <span>{{ parseTime(row.createTime,'{y}-{m}-{d}') }}</span>
        </template>
      </vxe-column>
      <vxe-column show-overflow="title" align="center" title="交货日期" prop="deliveryTime" width="120">
        <template #default="{ row }">
          {{ parseTime(row.deliveryTime, '{y}-{m}-{d}') }}
        </template>
      </vxe-column>
      <vxe-column field="cost" width="150" show-overflow="title" align="center" title="总计（含税）"></vxe-column>
      <vxe-column field="costExTax" width="160" show-overflow="title" align="center" title="总计（不含税）"></vxe-column>
      <vxe-column field="currency" show-overflow="title" align="center" title="币种类型" width="120"></vxe-column>
      <vxe-column field="createBy" show-overflow="title" align="center" title="制单" width="120"></vxe-column>
      <vxe-column field="auditor"  show-overflow="title" align="center" title="审核" width="120"></vxe-column>
      <vxe-column field="remark"  show-overflow="title" align="center" title="备注" width="120"></vxe-column>
      <vxe-column width="180" align="center" title="操作" fixed="right">
        <template #default="{ row }">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(row)"
          >{{row.poStatus!=='audited'?'查看':'修改'}}</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="row.poStatus=='audited'"
            @click="handleDelete(row)"
          >删除</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            @click="handleToExamine(row)"
          >审核</el-button> -->
          <el-button
            size="mini"
            type="text"
            @click="handlePrint(row)"
          >打印</el-button>
        </template>
      </vxe-column>
    </vxe-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <div class="app-container-footer">
      <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick" :lazy="true">
        <el-tab-pane label="采购订单明细" name="1"><baseInfo :key="'baseInfo0'" :cellId="cellId" /></el-tab-pane>
        <!-- <el-tab-pane label="采购收货（入库）" name="2">采购收货（入库）</el-tab-pane>
        <el-tab-pane label="退货明细" name="3">退货明细</el-tab-pane> -->
        <!-- <el-tab-pane label="付款单" name="1"><baseInfo /></el-tab-pane> -->
      </el-tabs>
    </div>

    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="1300px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="采购单据编号" prop="poCode">
              <el-input v-model="form.poCode" :disabled="form.id?true:false" placeholder="请输入采购单据编号" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item  label-width="80">
              <el-switch 
                :disabled="form.poCode != null"
                v-model="autoGenFlag"
                active-color="#13ce66"
                active-text="自动生成"
                @change="handleAutoGenChange(autoGenFlag)" >               
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="采购单据名称" prop="poName">
              <el-input v-model="form.poName" placeholder="请输入采购单据名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购申请类型" prop="poType">
              <el-select v-model="form.poType" placeholder="请选择采购申请类型">
                <el-option
                  v-for="dict in dict.type.purchase_request_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="需求仓库" prop="warehouseId">
              <el-select v-model="form.warehouseId" placeholder="请选择需求仓库">
                <el-option
                  v-for="dict in warehouseList"
                  :key="dict.warehouseId"
                  :label="dict.warehouseName"
                  :value="dict.warehouseId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商名称" prop="vendorId">
              <el-select v-model="form.vendorId" filterable placeholder="请选择供应商" @change="getVendorContactList(form.vendorId)">
                <el-option
                  v-for="dict in vendorList"
                  :key="dict.vendorId"
                  :label="dict.vendorName"
                  :value="dict.vendorId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="需求数量合计" prop="quantity">
              <el-input-number v-model="form.quantity" controls-position="right" :min="0" ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购员" prop="purchaser">
              <el-select v-model="form.purchaser" filterable placeholder="请选择采购员">
                <el-option
                  v-for="dict in userList"
                  :key="dict.userId"
                  :label="dict.userName"
                  :value="dict.nickName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交货日期" prop="deliveryTime">
              <el-date-picker
                v-model="form.deliveryTime"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="总计（含税）" prop="cost">
              <el-input v-model="form.cost" placeholder="请输入总计（含税）" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总计（不含税）" prop="costExTax">
              <el-input v-model="form.costExTax" placeholder="请输入总计（不含税）" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="币种名称" prop="currency">
              <el-select v-model="form.currency" placeholder="请选择币种">
                <el-option
                  v-for="dict in dict.type.currency_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-row>
      </el-form>

      <el-divider content-position="center">详情</el-divider> 
      <el-card shadow="always" class="box-card" v-if="open">
        <baseInfo 
          ref="baseInfo"
          :key="'baseInfo1'"
          :taxRate="taxRate"
          :type="title"
          :cellId="cellId" 
          :poStatus="poStatus" 
        />
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="form.id&&form.poStatus=='audited'" @click="submitForm1">提 交</el-button>
        <el-button type="primary" v-if="!form.id||form.poStatus=='audited'" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的设备数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link> -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPurchaseOrder,
  updatePurchaseOrder,
  detailPurchaseOrder,
  deletePurchaseOrder,
  addPurchaseOrder,
} from "@/api/mes/pro/purchaseOrder";
import { getToken } from "@/utils/auth";
import { listVendor } from "@/api/mes/md/vendor";
import { listWarehouse } from "@/api/mes/wm/warehouse";
import { listUser } from "@/api/system/user";
import {genCode} from "@/api/system/autocode/rule"
import baseInfo from "./components/baseInfo.vue";
export default {
  name: 'PurchaseOrder',
  dicts: ['purchase_request_status', 'currency_type', 'purchase_order_status'],
  components: { 
    baseInfo,
  },
  data() {
    return {
      //自动生成编码
      autoGenFlag:false,
      title: '',
      open: false,
      loading: false,
      total: 0,
      form: {},
      rules: {
        poCode:[{ required: true, message: '请输入采购订单编号', trigger: 'blur' }],
        poName:[{ required: true, message: '请输入采购订单名称', trigger: 'blur' }],
        poType:[{ required: true, message: '请选择采购订单类型', trigger: 'change' }],
        warehouseId:[{ required: true, message: '请选择仓库', trigger: 'change' }],
        vendorId:[{ required: true, message: '请选择供应商', trigger: 'change' }],
        quantity:[{ required: true, message: '请输入数量', trigger: 'blur' }],
        purchaser:[{ required: true, message: '请选择采购员', trigger: 'change' }],
        deliveryTime:[{ required: true, message: '请选择交货日期', trigger: 'change' }],
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        poCode: null,
        vendorNick: null,
        poStatusList: undefined,
        poCheckStatusList: undefined,
      },
      purchaseOrderList: [],
      vendorList: [],
      warehouseList: [],
      userList: [],
      activeName: '1',
      checked: false,
      checked1: false,
      checked2: false,
      checked3: false,
      checked4: false,
      checked5: false,
      checked6: false,
      cellId: null, //当前选中单元格的id
      baseTotal: 0, //采购订单条数
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/pro/po/importData"
      },
      options: [
        {
          value: '7',
          label: '7天'
        }, {
          value: '30',
          label: '30天'
        }, {
          value: '90',
          label: '90天'
        }, {
          value: '180',
          label: '180天'
        },
      ],
      columnConfig: {
        drag: true,
        resizable: true,
        storage: true,
        sortConfig: {
          trigger: 'cell',
          remote: true
        },
        align: 'center',
        headerAlign: 'center'
      },
      rowConfig: {
        drag: true,
        keyField: 'id',
        isHover: true,
        isCurrent: true,
      },
      ids: [], //选中的条目
      poStatus: '', //采购订单状态
      taxRate: 0, //税率
    }
  },
  created() {
    this.getList()
    listVendor({ pageNum: 1, pageSize: 9999 }).then(response => {
      this.vendorList = response.rows;
    })
    listWarehouse({ pageNum: 1, pageSize: 9999 }).then(response => {
      this.warehouseList = response.rows;
    })
    listUser({ pageNum: 1, pageSize: 9999 }).then(response => {
      this.userList = response.rows;
    })
    // console.log(this.dict.type.purchase_order_status);
  },
  methods: {
    getList(){
      this.loading = true;
      this.poCheckStatusList = []
      this.queryParams.poStatusList = this.queryParams.poStatusList?[this.queryParams.poStatusList]:null
      this.queryParams.poCheckStatusList = this.queryParams.poCheckStatusList?[this.queryParams.poCheckStatusList]:null
      listPurchaseOrder(this.queryParams).then(response => {
        this.purchaseOrderList = response.rows;
        this.$nextTick(() => {
          this.$refs.tableRef.setCurrentRow(this.purchaseOrderList[0]);
          this.poStatus = this.purchaseOrderList[0].poStatus;
        })
        if(response.rows?.length>0){
          this.cellId = response.rows[0].id;
        }
        this.total = response.total;
        console.log(response);
      }).finally(() => {
        this.loading = false;
        this.queryParams.poStatusList = this.queryParams.poStatusList?.join()
        this.queryParams.poCheckStatusList = this.queryParams.poCheckStatusList?.join()
      })
    },
    reset(){
      this.form = {
        id:null,
        poCode:null,
        poType:null,
        warehouseId:null,
        vendorId:null,
        quantity:null,
        purchaser:null,
        deliveryTime:null,
        cost:null,
        costExTax:null,
        currency:null,
        remark:null,
      };
      this.autoGenFlag = false;
      // this.$refs.form.resetFields();
    },
    handleAdd(){
      this.open = true;
      this.title = '新增';
      this.reset()
      this.poStatus = 'audited'
      this.$refs["form"]?.resetFields()
      this.form.purchaser = this.$store.state.user.nickName
      this.form.poType = this.dict.type.purchase_request_status[0].value
      this.form.deliveryTime = new Date().setDate(new Date().getDate() + 7)
      this.autoGenFlag = true
      this.handleAutoGenChange(this.autoGenFlag)
    },
    handleDelete(row){
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除该数据项？').then(function() {
        return deletePurchaseOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleUpdate(row){
      this.title = '修改';
      this.reset();
      this.cellId = row.id;
      this.open = true;
      this.form = { ...row };
    },
    handleToExamine(row){
      console.log(row);
    },
    handleAntiAudit(row){
      console.log(row);
    },
    handleQuery(){
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery(){
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        poCode: null,
        vendorNick: null,
        poStatusList: undefined,
        poCheckStatusList: undefined,
      },
      this.getList();
    },
    submitForm(){
      this.$refs["form"].validate(valid => {
        const res = this.$refs.baseInfo.submitForm()
        console.log('params', this.$refs.baseInfo.tableDataList.map(item => {
          const copy = { ...item }
          delete copy.id
          return copy
        }));
        if(!res) return this.$modal.msgWarning("请在表格里填写正确的订购数量")
        if (valid) {
          if (this.form.id != null) {
            const params = {
              purchaseOrder: { ...this.form },
              purchaseOrderLines: this.$refs.baseInfo.tableDataList.map(item => {
                const copy = { ...item }
                delete copy.id
                return copy
              })
            }
            updatePurchaseOrder(params).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            const params = {
              purchaseOrder: { ...this.form },
              purchaseOrderLines: this.$refs.baseInfo.tableDataList.map(item => {
                const copy = { ...item }
                delete copy.id
                return copy
              })
            }
            addPurchaseOrder(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      })
    },
    cancel(){
      this.$refs["form"].resetFields();
      this.open = false;
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag){
      if(autoGenFlag){
        genCode('PURCHASE_ORDER_CODE').then(response =>{
          this.form.poCode = response;
        });
      }else{
        this.form.poCode = null;
      }
    },
    cellClickEvent({row}){
      this.cellId = row.id;
      this.poStatus = row.poStatus;
      this.handleClick({name:'1'})
      console.log(row);
    },
    checkboxChangeEvent(checked){
      this.ids = checked.records.map(item => item.id)
      console.log(checked.records, this.ids);
    },
    checkboxAll(checked){
      this.ids = checked.records.map(item => item.id)
      console.log(checked.records, this.ids)
    },
    handleClick(tab, event) {
      switch (tab.name) {
        case '1':
          console.log('基础信息');
          break;
        case '2':
          console.log('2');
          break;
        default:
          break;
      }
    },
    // 订单明细
    getBaseInfoList(params={pageNum:1,pageSize:10}){
      detailPurchaseOrder(this.cellId, params).then(response => {
        this.baseTotal = response.total;
        console.log(response);
      })
    },
    handleInput(){
      this.upload.title = "数据导入";
      this.upload.open = true;
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    handlePrint(row){
      console.log(row, window.location);
      window.open(window.location.origin + window.location.pathname + '#/printTemplate?poId=' + row.id + '&type=in', '_blank');
    },
    submitForm1(){
      this.$confirm('提交之后不允许在修改，确定要修改吗？').then(() => {
        this.form.poStatus = 'not_in'
        const params = {
          purchaseOrder: { ...this.form },
          purchaseOrderLines: this.$refs.baseInfo.tableDataList.map(item => {
            const copy = { ...item }
            delete copy.id
            return copy
          })
        }
        updatePurchaseOrder(params).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      })
    },
    getVendorContactList(id){
      this.vendorList.forEach(item => {
        if(item.vendorId === id){
          this.taxRate = item.taxRate
        }
      })
      // console.log(this.taxRate);
    }
  }
}
</script>

<style lang="scss" scoped>
/* 选中行的高亮颜色 */
// .el-table__row.current-row {
//   background-color: #f0f9eb !important; /* 绿色背景 */
// }
</style>